<template>
  <!-- 有订单数据时展示 -->
  <el-row v-if="myOrderList.length" class="order-list">
    <el-col :span="24" class="order-container">
      <!-- 订单表头区域（包含标题和筛选） -->
      <el-row class="order-header">
        <!-- 标题部分，占比可根据需求调整 -->
        <el-col :span="8" class="order-title">
          <span class="title-text">我的订单{{ filteredTotal > 0 ? `(${filteredTotal})` : '' }}</span>
        </el-col>
        <!-- 筛选 tabs 部分，占比可根据需求调整 -->
        <el-col :span="16" class="order-tabs">
          <el-radio-group v-model="activeTab" class="tabs-group">
            <el-radio value="all" class="tab-item">全部订单</el-radio>
            <el-radio value="waitToPay" class="tab-item">待支付</el-radio>
            <el-radio value="waitToDeliver" class="tab-item">待发货</el-radio>
            <el-radio value="waitToReceive" class="tab-item">待收货</el-radio>
            <el-radio value="finished" class="tab-item">已完成</el-radio>
            <el-radio value="refund" class="tab-item">售后</el-radio>
            <el-radio value="cancel" class="tab-item">已取消</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 订单列表表格 -->
      <el-table :data="tableData" stripe :fit="true" class="order-table" style="width: 100%; margin-top: 10px">

        <!-- 订单日期与单号列 -->
        <el-table-column label="订单信息" min-width="200px">
          <template #default="scope">
            <div>
              <p>订单号：{{ scope.row.orderId }}</p>
            </div>
          </template>
        </el-table-column>

        <!-- 商品信息列 -->
        <el-table-column label="商品详情" min-width="300px">
          <template #default="scope">
            <div class="order-item" v-for="item in scope.row.orderitems">
              <img :src="item.bookcover ? item.bookcover : nullImageUrl" @error="handleImageError" alt="商品图"
                class="order-item-img" />
              <div class="order-item-info">
                <p>商品名称：《{{ item.booktitle }}》</p>
                <p>商品数量：{{ item.quantity }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 收货信息列 -->
        <el-table-column label="收货信息" min-width="200px">
          <template #default="scope">
            <div>
              <p>收货人：{{ scope.row.consignee }}</p>
              <p>联系电话：{{ scope.row.phone }}</p>
              <p>收货地址：{{ scope.row.addressVo.province }} {{ scope.row.addressVo.city }} {{ scope.row.addressVo.district
              }} {{ scope.row.addressVo.detail }}</p>
            </div>
            <!-- 三种支付方式 -->

            <p>
              支付方式：
              <span v-if="scope.row.payMethod === 1">微信</span>
              <span v-if="scope.row.payMethod === 2">支付宝</span>
              <span v-if="scope.row.payMethod === 3">银行卡</span>
            </p>
          </template>
        </el-table-column>

        <!-- 金额列 -->
        <el-table-column label="金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>


        <!-- 操作列 -->
        <el-table-column label="操作" width="120"
          v-if="activeTab !== 'refund' && activeTab !== 'cancel' && activeTab !== 'waitToDeliver'">
          <template #default="scope">
            <el-row>
              <el-button v-if="activeTab === 'finished' || (activeTab === 'all' && (scope.row.orderStatus === 4))"
                type="primary" size="small" @click="handleAfterSale(scope.row)">售后</el-button>
              <el-button v-if="activeTab === 'waitToReceive' || (activeTab === 'all' && (scope.row.orderStatus === 3))"
                type="primary" size="small" @click="handleConfirmReceive(scope.row)">
                确认收货
              </el-button>
              <!-- 去支付 -->
              <el-button v-else-if="activeTab === 'waitToPay' || (activeTab === 'all' && scope.row.orderStatus === 1)"
                type="primary" size="small" :disabled="isOrderExpired(scope.row)" @click="handlePay(scope.row)">
                去支付
              </el-button>
            </el-row>
          </template>
        </el-table-column>


        <!-- 订单状态列 -->
        <el-table-column label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.orderStatus)">
              {{ orderStatusMap.get(scope.row.orderStatus) || "未知状态" }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 售后结果列 -->
        <el-table-column label="售后情况" width="160" v-if="activeTab === 'refund'">
          <template #default="scope">
            <el-row v-if="scope.row.orderStatus === 6">
              <el-col>
                <!-- 售后中 -->
                <el-tag type="error">后台审核中</el-tag><br>
                <span class="order-item-refund-reason"> {{ scope.row.reason ? `我的售后理由： ${scope.row.reason}` :
                  '此次申请售后你未填写售后理由'
                }}</span>
              </el-col>
            </el-row>
            <el-row v-if="scope.row.orderStatus === 7">
              <!-- 售后完成的情况 -->
              <!-- <el-tag type="success">后台审核完成</el-tag><br> -->
              <el-col>
                <span class="order-item-refund-reason-success" v-if="scope.row.adminAgreement === 1">退货成功</span>
                <span class="order-item-refund-reason" v-else> {{ scope.row.adminReason }}</span>

              </el-col>
            </el-row>
          </template>
        </el-table-column>


        <!-- 订单失效列 -->
        <el-table-column label="订单失效截止时间" width="120" v-if="activeTab === 'waitToPay'">
          <template #default="scope">
            <span v-html="getExpireTimeDisplay(scope.row)"></span>
          </template>
        </el-table-column>




        <!-- 删除列 -->
        <el-table-column label="删除" width="120">
          <template #default="scope">
            <el-row>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)"
                v-if="activeTab === 'finished' || activeTab === 'cancel' || (activeTab === 'all' && (scope.row.orderStatus === 5 || scope.row.orderStatus === 4 || scope.row.orderStatus === 7)) || (activeTab === 'refund' && (scope.row.orderStatus === 7))">
                删除订单
              </el-button>
              <el-button
                v-else-if="activeTab === 'waitToDeliver' || activeTab === 'waitToPay' || activeTab === 'waitToReceive' || (activeTab === 'all' && (scope.row.orderStatus === 1 || scope.row.orderStatus === 2 || scope.row.orderStatus === 3)) || (activeTab === 'refund' && (scope.row.orderStatus === 6))"
                type="danger" size="small" @click="cancelExpiredOrder(scope.row.orderId)">取消订单</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row class="pagination" type="flex" justify="end" style="margin-top: 10px">
        <el-col>
          <el-pagination background :current-page="currentPage" :page-size="pageSize" :total="filteredTotal"
            @current-change="handlePageChange" />
        </el-col>
      </el-row>
    </el-col>
  </el-row>

  <!-- 无订单数据时展示空状态 -->
  <el-row v-else class="order-empty">
    <el-col>
      <el-empty description="当前无订单" :image-size="470" />
    </el-col>
  </el-row>

  <el-dialog v-model="dialogFormVisible" title="售后申请" width="500">
    <el-form>
      <el-form-item label="售后原因" label-width="140px">
        <el-input v-model="afterSaleReason" placeholder="请输入售后原因" :maxlength="200" type="textarea" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消售后</el-button>
        <el-button type="primary" @click="handleAfterSaleSubmit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userOrderStore } from '@/stores/order'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
import { UpdateOrderStatusToCancel, payOrder, UpdateOrderStatusToComplete } from '@/api/order'
const orderStore = userOrderStore()

const myOrderList = ref([])
const orderTimers = ref({}) // 存储订单定时器
const orderExpireStatus = ref({}) // 存储订单过期状态


// 使用 Vite 的 URL 解析方式处理静态资源
const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;

// 处理图片加载失败事件
const handleImageError = (event) => {
  // 直接设置为默认图片
  event.target.src = defaultImageUrl;
};

// 订单状态标签类型style
const getStatusTagType = (status) => {
  switch (status) {
    case 1: return 'danger'
    case 2: return 'primary'
    case 3: return 'warning'
    case 4: return 'success'
    case 5: return 'info'
    case 6: return 'warning'
    case 7: return 'success'
    default: return 'primary'
  }
}

// 订单状态映射
const orderStatusMap = ref(new Map([
  [1, '待支付'],
  [2, '待发货'],
  [3, '待收货'],
  [4, '已完成'],
  [5, '已取消'],
  [6, '售后中'],
  [7, '售后完成'],
]))

// 订单筛选
const activeTab = ref('all')
const filteredByStatus = computed(() => {
  return myOrderList.value.filter(item => {
    if (activeTab.value === 'waitToPay') return item.orderStatus === 1
    if (activeTab.value === 'waitToDeliver') return item.orderStatus === 2
    if (activeTab.value === 'waitToReceive') return item.orderStatus === 3
    if (activeTab.value === 'finished') return item.orderStatus === 4
    if (activeTab.value === 'cancel') return item.orderStatus === 5
    if (activeTab.value === 'refund') return item.orderStatus === 6 || item.orderStatus === 7
    return true
  })
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(4)
const filteredTotal = computed(() => filteredByStatus.value.length)
const tableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value

  return filteredByStatus.value.slice(startIndex, startIndex + pageSize.value)
})
const handlePageChange = (val) => {
  currentPage.value = val
}


// 初始化订单倒计时
const initOrderTimers = () => {
  myOrderList.value.forEach(order => {
    if (order.orderStatus === 1 && !orderTimers.value[order.orderId]) {
      startOrderTimer(order)
    }
  })
}

// 启动订单倒计时
const startOrderTimer = (order) => {
  const timer = setInterval(() => {
    const isExpired = checkOrderExpire(order)
    if (isExpired) {
      clearInterval(timer)
      delete orderTimers.value[order.orderId]
      cancelExpiredOrder(order.orderId)
    } else {
      // 更新订单显示时间，触发UI刷新
      updateOrderDisplayTime(order)
    }
  }, 1000)
  orderTimers.value[order.orderId] = timer
}

// 检查订单是否过期
const checkOrderExpire = (order) => {
  const now = new Date()
  const payTime = new Date(order.datetime)
  const expireTime = new Date(payTime)
  expireTime.setMinutes(expireTime.getMinutes() + 10) // 10分钟有效期
  return now >= expireTime
}

// 更新订单显示时间
const updateOrderDisplayTime = (order) => {
  const index = myOrderList.value.findIndex(item => item.orderId === order.orderId)
  if (index !== -1) {
    // 创建新对象保持响应式
    const updatedOrder = { ...myOrderList.value[index] }
    myOrderList.value.splice(index, 1, updatedOrder)
  }
}

// 获取过期时间显示（添加动画效果）
const getExpireTimeDisplay = (order) => {
  const now = new Date()
  const payTime = new Date(order.datetime)
  const expireTime = new Date(payTime)
  expireTime.setMinutes(expireTime.getMinutes() + 10)

  const remainingMs = expireTime - now
  if (remainingMs <= 0) {
    orderExpireStatus.value[order.orderId] = true
    return '<span class="text-red-500 font-bold">已过期</span>'
  }

  const hours = Math.floor(remainingMs / (1000 * 60 * 60))
  const minutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000)

  const displayText = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  orderExpireStatus.value[order.orderId] = false

  // 剩余1分钟内显示橙色并添加脉冲动画
  if (remainingMs < 60 * 1000) {
    return `<span class="text-orange-500 animate-pulse font-bold">${displayText}</span>`
  }
  return displayText
}

// 判断订单是否过期
const isOrderExpired = (order) => {
  return orderExpireStatus.value[order.orderId] || checkOrderExpire(order)
}

// 取消过期订单
const cancelExpiredOrder = async (orderId) => {
  try {
    console.log('取消订单请求参数：', orderId);
    const response = await UpdateOrderStatusToCancel(orderId)
    console.log('取消订单请求的结果：', response);
    if (response.data.code === 0) {
      await orderStore.fetchOrders()
      myOrderList.value = orderStore.orders
      ElMessage.success('订单已取消')
    } else {
      ElMessage.error('取消订单失败')
      // throw new Error('取消订单失败')
    }
    window.location.reload();
  } catch (error) {
    console.error('取消订单错误:', error)
  }
}

// 点击去支付
const handlePay = async (row) => {
  console.log("付款行", row);
  //弹窗确认支付
  ElMessageBox.alert('确认付款吗？', '温馨提示：模拟付款过程', {
    confirmButtonText: '点击立即付款',
    callback: async (action) => {
      if (isOrderExpired(row)) {
        ElMessage.error('订单已过期，无法支付')
        return
      } else {
        if (action === 'confirm') {
          console.log('点击去支付本行orderID：', row.orderId);
          const result = await payOrder(row.orderId)
          if (result.data.code === 0) {
            await orderStore.fetchOrders()
            myOrderList.value = orderStore.orders
            ElMessage({
              type: 'success',
              message: `付款成功`,
              plain: true
            })
          } else {
            ElMessage({
              type: 'error',
              message: `付款过程出错`,
              plain: true
            })
          }
          console.log('支付结果：', result);

        } else {
          ElMessage({
            type: 'info',
            message: `取消付款`,
            plain: true
          })
        }

      }
    },
  })




}

// 售后弹窗
const dialogFormVisible = ref(false)
const afterSaleReason = ref('')
const afterSaleOrderId = ref()

//售后按钮
const handleAfterSale = (row) => {
  //点击售后弹窗
  dialogFormVisible.value = true
  // 获取售后订单ID
  afterSaleOrderId.value = row.orderId
}
//调用售后接口
const handleAfterSaleSubmit = async () => {
  const orderData = {
    orderId: afterSaleOrderId.value,
    userId: userStore.userInfo.userId,
    reason: afterSaleReason.value,
  }
  console.log('售后申请参数：', orderData);
  if (orderData.reason === '') {
    ElMessage.error('请填写售后原因')
    return
  }
  await orderStore.applyAfterSale(orderData)
  myOrderList.value = orderStore.orders
  dialogFormVisible.value = false
  window.location.reload();

}
//确认收货按钮
const handleConfirmReceive = async (row) => {
  console.log('点击确认收货这一行按钮', row)
  const result = await UpdateOrderStatusToComplete(row.orderId)
  if (result.data.code === 0) {
    orderStore.fetchOrders()
    myOrderList.value = orderStore.orders
    ElMessage.success('确认收货成功')
  } else {
    ElMessage.error('确认收货失败')
  }
  window.location.reload();

}

const handleDelete = async (row) => {
  const deleteResult = await orderStore.deleteOrder(row.orderId)
  if (deleteResult) {
    myOrderList.value = orderStore.orders
    ElMessage.success('删除成功')
    window.location.reload();
  }
}

// 监听标签切换，重置分页状态
watch(activeTab, (newVal) => {
  if (newVal !== activeTab.value) {
    currentPage.value = 1
    nextTick(() => {
      initOrderTimers() // 切换标签后重新初始化倒计时
    })
  }
})

onMounted(async () => {
  await orderStore.fetchOrders()
  myOrderList.value = orderStore.orders
  initOrderTimers() // 初始化订单倒计时
})

onUnmounted(() => {
  // 组件卸载时清除所有定时器
  Object.values(orderTimers.value).forEach(timer => clearInterval(timer))
  orderTimers.value = {}
})
</script>

<style scoped lang="less">
@primary-color: rgb(74, 144, 226);
@border-color: #ebedf0;
@bg-light: rgba(74, 144, 226, .1);
@spacing: 15px;

.order-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 0 3px rgba(66, 66, 66, 0.3);
}

.order-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid @border-color;
  background-color: @bg-light;

  .order-title {
    .title-text {
      font-size: 21px;
      font-weight: 700;
      color: #4e4e4e;
      padding: 0 20px;
    }
  }

  .order-tabs {
    .tabs-group {
      display: flex;
      gap: 20px;
      justify-content: flex-end;
      padding-right: 20px;
    }

    .tab-item {
      color: #666;
      cursor: pointer;

      &.is-checked {
        color: @primary-color;
      }
    }
  }
}

.order-table {
  margin-top: 15px;
  border-radius: 4px;
  overflow: hidden;

  .el-table__header {
    background-color: @bg-light;

    th {
      border-bottom: 2px solid @border-color;
      font-weight: 500;
      padding: 12px 16px;
      color: #0328cd;
    }
  }

  .el-table__body {
    tr {
      &:hover {
        background-color: #f4f1f3;
      }

      &:not(:last-child) {
        border-bottom: 1px solid @border-color;
      }

      .order-item {
        display: flex;
        align-items: center;
        gap: @spacing;
        padding: 12px 16px;

        .order-item-img {
          width: 80px;
          height: 80px;
          object-fit: contain;
          border: 1px solid @border-color;
          border-radius: 4px;
        }

        .order-item-info {
          line-height: 1.5;
          color: #e10f0f;

          p {
            color: #666;
            font-size: 14px;
            margin-top: 5px;
          }
        }
      }
    }
  }

  .el-table__cell .el-button {
    color: @primary-color;
    padding: 0 8px;
    margin: 3px 0;
    font-size: 14px;
    color: rgb(255, 255, 255);
  }
}

.pagination {
  .el-pagination {
    .el-pager li {
      color: #666;
    }

    .el-pager li.active {
      color: @primary-color;
    }
  }
}

.order-empty {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
}

// .order-item-refund-reason-fail {
//   color: #d51212;
//   font-size: 12px;
// }

.order-item-refund-reason {
  color: #bbbbbb;
  font-size: 12px;
}

.order-item-refund-reason-success {
  color: #00b300;
  font-size: 12px;
}
</style>